﻿@inherits BaseDataEditor

@if (Options != null)
{
    var index = 0;

    var value = GetValueAsObject();

    <div class="form-control form-control-select-list @(CssHelper.GetValidationClass(State))">
        @foreach (var option in Options)
        {
            index++;

            <div class="form-check">
                <div class="row">
                    <div class="col">
                        <label class="form-check-label row" for="@group-option@(index)">
                            <input class="form-check-input"
                                   type="radio"
                                   value=@option.Id
                                   id="@group-option@(index)"
                                   name=@group
                                   checked=@(option.Id.Equals(value))
                                   disabled=@IsDisabled
                                   @onchange=@(async args => SetValueFromObject(option.Id)) />
                            @option.Labels.First()
                        </label>
                    </div>
                    @foreach (var label in option.Labels.Skip(1))
                    {
                        <div class="col">
                            <label class="form-check-label" for="@group-option@(index)">
                                @label
                            </label>
                        </div>
                    }
                </div>
            </div>
        }
    </div>

    @foreach (var message in GetValidationMessages())
    {
        <div class="invalid-feedback">
            @message
        </div>
    }
}
@code {

    private string group = Guid.NewGuid().ToString().Replace("-", "");

    private IEnumerable<IElement>? Options;

    protected override async Task OnInitializedAsync()
    {
        if (DataCollection != null)
        {
            DataCollection.OnDataChange += async (s, a) => await UpdateOptionsAsync();

            await DataCollection.SetEntityAsync(EditContext, Parent);
            await UpdateOptionsAsync();
        }
    }

    private async Task UpdateOptionsAsync()
    {
        if (DataCollection == null)
        {
            return;
        }

        await InvokeAsync(async () =>
        {
            Options = await DataCollection.GetAvailableElementsAsync();
            StateHasChanged();
        });
    }
}
